package com.sto.stoapp.util;

import android.os.Environment;
import android.os.StatFs;

import java.io.File;

/**
 * Created by cjb on 2016/6/28 0028.
 */
public class MemorySpaceCheck {
    private static MemorySpaceCheck memorySpaceCheck;

    public static MemorySpaceCheck getInstance()
    {
        if (memorySpaceCheck == null) {
            memorySpaceCheck = new MemorySpaceCheck();
        }
        return memorySpaceCheck;
    }

    private long getAvailableSize(String path)
    {
        StatFs fileStats = new StatFs(path);
        fileStats.restat(path);
        return fileStats.getAvailableBlocks() * fileStats.getBlockSize();
    }

    private long getTotalSize(String path)
    {
        StatFs fileStats = new StatFs(path);
        fileStats.restat(path);
        return fileStats.getBlockCount() * fileStats.getBlockSize();
    }

    public long getSDAvailableSize()
    {
        if (Environment.getExternalStorageState().equals(
                "mounted")) {
            return getAvailableSize(Environment.getExternalStorageDirectory()
                    .toString());
        }

        return 0L;
    }

    public long getSystemAvailableSize()
    {
        return getAvailableSize("/data");
    }

    public boolean hasEnoughMemory(String filePath)
    {
        File file = new File(filePath);
        long length = file.length();
        if ((filePath.startsWith("/sdcard")) ||
                (filePath.startsWith("/mnt/sdcard"))) {
            return getSDAvailableSize() > length;
        }
        return getSystemAvailableSize() > length;
    }

    public long getSDTotalSize()
    {
        if (Environment.getExternalStorageState().equals(
                "mounted")) {
            return getTotalSize(Environment.getExternalStorageDirectory()
                    .toString());
        }

        return 0L;
    }

    public long getSysTotalSize()
    {
        return getTotalSize("/data");
    }
}
